import React, {
  forwardRef,
  useCallback,
  useContext,
  useImperativeHandle,
  useState,
} from 'react';
import dragOperationSlice from '../redux/toolKitSlice/dragOperation';
import Card from './Card';
import TransferBoxContext from './TransferBoxContext';
import type { RefFn } from './index';

const DEFAULTLEFTCARDS = [
  {
    id: 1,
    text: 'text1 S1-T0',
  },
  {
    id: 2,
    text: 'text2 S3-T2',
  },
  {
    id: 3,
    text: 'text3 S5-T4',
  },
];

const Left = forwardRef<RefFn>((props, ref) => {
  const { onDeletInsertItem, store } = useContext(TransferBoxContext);
  const [overIndex, setOverIndex] = useState<number>();
  const [cards, setCards] =
    useState<{ id: number; text: string }[]>(DEFAULTLEFTCARDS);

  //排序
  const handleMoveCard = useCallback<
    (dragIndex: number, hoverIndex: number) => void
  >(
    (dragIndex, hoverIndex) => {
      const dragItem = cards.splice(dragIndex, 1)[0];
      cards.splice(hoverIndex, 0, dragItem);
      // console.log('--dragIndex--hoverIndex--:', dragIndex, hoverIndex);
      setCards([...cards]);
    },
    [cards],
  );

  //删除
  useImperativeHandle(ref, () => ({
    handleDeletItem: (id) => {
      const newCards = cards.filter((carItem) => carItem.id !== id);
      setCards(newCards);
    },
  }));

  //新增
  const handleAddCard = useCallback(
    (inSertItem: any, hoverIndex: number, targetParent: 'left' | 'right') => {
      cards.splice(hoverIndex + 1, 0, inSertItem);
      const newCards = [...cards];
      console.log(
        '--left--inSertItem--hoverIndex--handleAddCard--newCards----:',
        inSertItem,
        hoverIndex,
        newCards,
      );
      setCards(newCards);
      //右边删除
      onDeletInsertItem(inSertItem, targetParent);
    },
    [cards],
  );

  store.subscribe(() => {
    const { dropIndex, dropParentName } =
      store.getState().dragOperationStore ?? {};
    // overIndex = dropIndex;
    // console.log('--Left--store变化--dropIndex--:', dropIndex)
    setOverIndex(dropParentName === 'left' ? dropIndex : undefined);
  });

  const handleDragEnter: React.DragEventHandler<HTMLElement> = (e) => {
    console.log('--left--ul--handleDragEnter--cards--:', cards);
    if (!cards || cards.length <= 0) {
      e.dataTransfer.dropEffect = 'move';
      // 放置完毕，当前Card已经被删除， handleDrop/ handleDragEnd不会执行
      const operationStore = store.getState().dragOperationStore;
      // console.log('--left--ul--operationStore--:', operationStore);
      const { dragSouce } = operationStore;
      setCards([dragSouce]);
      //右边删除
      onDeletInsertItem(dragSouce, 'left');

      store.dispatch(dragOperationSlice.actions.endDrag({}));
    }
  };

  //onDrop={handleDrop}
  // const handleDrop: React.DragEventHandler<HTMLElement> = (e) => {
  //   console.log('--left--ul--handleDrop--cards--第一个card拖过来的时候不执行----');
  // }

  return (
    <ul className="sort-h5-card-list" onDragEnter={handleDragEnter}>
      {cards.map((card, i) => (
        <Card
          {...card}
          index={i}
          key={card.id}
          onMoveCard={handleMoveCard}
          store={store}
          parentName="left"
          onAddCard={handleAddCard}
          overIndex={overIndex}
        />
      ))}
    </ul>
  );
});

export default Left;
